package edu.hunau.cxb19.oop.class27;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

/**
 *
 * @author hb
 *
 *         2020-04-01 14:48:31
 */
public class ObjectStreamTest {

	/**
	 * 将User的实例对象写入到demo\obj.data文件中
	 */
	@Test
	public void obejctToStreamTest() {
		try (FileOutputStream fos = new FileOutputStream(".\\demo\\obj.data");
				ObjectOutputStream oos = new ObjectOutputStream(fos);) {
			User u = new User(1001, "haoren");
			// 实现对象的序列化
			oos.writeObject(u);
			oos.flush();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Test
	public void objectReaderTest() {
		try (FileInputStream fis = new FileInputStream(".\\demo\\obj.data");
				ObjectInputStream ois = new ObjectInputStream(fis);) {

			Object obj = ois.readObject();
			if (obj instanceof User) {
				User u = (User) obj;
				System.out.println(u);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Object copyObject(Object obj) {
		try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream(baos);) {

			// 将对象写入到临时输出流中
			oos.writeObject(obj);
			// 获得数据
			byte[] datas = baos.toByteArray();
			try (ByteArrayInputStream bais = new ByteArrayInputStream(datas);
					ObjectInputStream ois = new ObjectInputStream(bais);) {
				return ois.readObject();
			}

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Test
	public void testClone() {
		ArrayList<User> arrayList = new ArrayList<User>();
		arrayList.add(new User(1001, "haoren01"));
		arrayList.add(new User(1002, "haoren02"));
		arrayList.add(new User(1003, "haoren03"));

		// 通过Object提供的clone方法
		ArrayList<User> copyList = (ArrayList<User>) arrayList.clone();
		System.out.println(arrayList == copyList);// false

		System.out.println(arrayList.get(0) == copyList.get(0));// true

		ArrayList<User> copyConts = new ArrayList<User>(arrayList);
		System.out.println(arrayList == copyConts);// false

		System.out.println(arrayList.get(0) == copyConts.get(0));// true

		ArrayList<User> deepCopy = (ArrayList<User>) copyObject(arrayList);
		System.out.println(arrayList == deepCopy);// false
		System.out.println(arrayList.get(0) == deepCopy.get(0));// false

	}

}
